home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / hplip / base / tui.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  12.7 KB  |  419 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import sys
  5. import re
  6. from g import *
  7. import pexpect
  8. import utils
  9.  
  10. def enter_yes_no(question, default_value = 'y', choice_prompt = None):
  11.     if type(default_value) == type(''):
  12.         if default_value == 'y':
  13.             default_value = True
  14.         else:
  15.             default_value = False
  16.     
  17.     if choice_prompt is None:
  18.         if default_value:
  19.             question += ' (y=yes*, n=no, q=quit) ? '
  20.         else:
  21.             question += ' (y=yes, n=no*, q=quit) ? '
  22.     else:
  23.         question += choice_prompt
  24.     while True:
  25.         
  26.         try:
  27.             user_input = raw_input(log.bold(question)).lower().strip()
  28.         except EOFError:
  29.             continue
  30.  
  31.         if not user_input:
  32.             return (True, default_value)
  33.         if user_input == 'n':
  34.             return (True, False)
  35.         if user_input == 'y':
  36.             return (True, True)
  37.         if user_input in ('q', 'c'):
  38.             return (False, default_value)
  39.         log.error("Please press <enter> or enter 'y', 'n', or 'q'.")
  40.         continue
  41.         user_input in ('q', 'c')
  42.  
  43.  
  44. def enter_range(question, min_value, max_value, default_value = None):
  45.     while True:
  46.         
  47.         try:
  48.             user_input = raw_input(log.bold(question)).lower().strip()
  49.         except EOFError:
  50.             continue
  51.  
  52.         if not user_input:
  53.             if default_value is not None:
  54.                 return (True, default_value)
  55.         
  56.         if user_input == 'q':
  57.             return (False, default_value)
  58.         
  59.         try:
  60.             value_int = int(user_input)
  61.         except ValueError:
  62.             user_input == 'q'
  63.             user_input == 'q'
  64.             log.error('Please enter a number between %d and %d, or "q" to quit.' % (min_value, max_value))
  65.             continue
  66.         except:
  67.             user_input == 'q'
  68.  
  69.         if value_int < min_value or value_int > max_value:
  70.             log.error('Please enter a number between %d and %d, or "q" to quit.' % (min_value, max_value))
  71.             continue
  72.         
  73.         return (True, value_int)
  74.  
  75.  
  76. def enter_choice(question, choices, default_value = None):
  77.     if 'q' not in choices:
  78.         choices.append('q')
  79.     
  80.     for x in choices:
  81.         []([] % (_[1](_[1]["'%s'" % x]), default_value))
  82.         ', '.join
  83.  
  84.  
  85. def title(text):
  86.     log.info('')
  87.     log.info('')
  88.     log.info(log.bold(text))
  89.     log.info(log.bold('-' * len(text)))
  90.  
  91.  
  92. def header(text):
  93.     c = len(text)
  94.     log.info('')
  95.     log.info('-' * (c + 4))
  96.     log.info('| ' + text + ' |')
  97.     log.info('-' * (c + 4))
  98.     log.info('')
  99.  
  100.  
  101. def load_paper_prompt():
  102.     return continue_prompt('A page will be printed.\nPlease load plain paper into the printer.')
  103.  
  104.  
  105. def load_scanner_for_align_prompt():
  106.     return continue_prompt("Load the alignment page on the scanner bed and push the 'Scan' or 'Enter' button on the printer to complete the alignment.")
  107.  
  108.  
  109. def load_photo_paper_prompt():
  110.     return continue_prompt('A page will be printed.\nPlease load HP Advanced Photo Paper - Glossy into the printer.')
  111.  
  112.  
  113. def continue_prompt(prompt = ''):
  114.     while True:
  115.         
  116.         try:
  117.             x = raw_input(log.bold(prompt + " Press <enter> to continue or 'q' to quit: ")).lower().strip()
  118.         except EOFError:
  119.             continue
  120.  
  121.         if not x:
  122.             return True
  123.         if x == 'q':
  124.             return False
  125.         log.error("Please press <enter> or enter 'q' to quit.")
  126.         continue
  127.         x == 'q'
  128.  
  129.  
  130. def enter_regex(regex, prompt, pattern, default_value = None):
  131.     re_obj = re.compile(regex)
  132.     while True:
  133.         
  134.         try:
  135.             x = raw_input(log.bold(prompt))
  136.         except EOFError:
  137.             continue
  138.  
  139.         if not x and default_value is not None:
  140.             return (default_value, x)
  141.         if x == 'q':
  142.             return (False, default_value)
  143.         match = re_obj.search(x)
  144.         return (True, x)
  145.         None if not match else default_value is not None
  146.  
  147.  
  148. def ttysize():
  149.     
  150.     try:
  151.         import commands
  152.         ln1 = commands.getoutput('stty -a').splitlines()[0]
  153.         vals = {
  154.             'rows': None,
  155.             'columns': None }
  156.         for ph in ln1.split(';'):
  157.             x = ph.split()
  158.             if len(x) == 2:
  159.                 vals[x[0]] = x[1]
  160.                 vals[x[1]] = x[0]
  161.                 continue
  162.         
  163.         return (int(vals['rows']), int(vals['columns']))
  164.     except TypeError:
  165.         return (40, 64)
  166.  
  167.  
  168.  
  169. class ProgressMeter(object):
  170.     
  171.     def __init__(self, prompt = 'Progress:'):
  172.         self.progress = 0
  173.         self.prompt = prompt
  174.         self.prev_length = 0
  175.         self.spinner = '\\|/-\\|/-*'
  176.         self.spinner_pos = 0
  177.         self.max_size = ttysize()[1] - len(prompt) - 25
  178.         self.update(0)
  179.  
  180.     
  181.     def update(self, progress, msg = ''):
  182.         self.progress = progress
  183.         x = self.progress * self.max_size / 100
  184.         if x > self.max_size:
  185.             x = self.max_size
  186.         
  187.         if self.progress >= 100:
  188.             self.spinner_pos = 8
  189.             self.progress = 100
  190.         
  191.         sys.stdout.write('\x08' * self.prev_length)
  192.         y = '%s [%s%s%s] %d%%  %s   ' % (self.prompt, '*' * (x - 1), self.spinner[self.spinner_pos], ' ' * (self.max_size - x), self.progress, msg)
  193.         sys.stdout.write(y)
  194.         sys.stdout.flush()
  195.         self.prev_length = len(y)
  196.         self.spinner_pos = (self.spinner_pos + 1) % 8
  197.  
  198.  
  199.  
  200. class Formatter(object):
  201.     
  202.     def __init__(self, margin = 2, header = None, min_widths = None, max_widths = None):
  203.         self.margin = margin
  204.         self.header = header
  205.         self.rows = []
  206.         self.max_widths = max_widths
  207.         self.min_widths = min_widths
  208.  
  209.     
  210.     def add(self, row_data):
  211.         self.rows.append(row_data)
  212.  
  213.     
  214.     def output(self):
  215.         if self.rows:
  216.             num_cols = len(self.rows[0])
  217.             for r in self.rows:
  218.                 if len(r) != num_cols:
  219.                     log.error('Invalid number of items in row: %s' % r)
  220.                     return None
  221.             
  222.             if len(self.header) != num_cols:
  223.                 log.error('Invalid number of items in header.')
  224.             
  225.             min_calc_widths = []
  226.             for c in self.header:
  227.                 header_parts = c.split(' ')
  228.                 max_width = 0
  229.                 for x in header_parts:
  230.                     max_width = max(max_width, len(x))
  231.                 
  232.                 min_calc_widths.append(max_width)
  233.             
  234.             max_calc_widths = []
  235.             for x, c in enumerate(self.header):
  236.                 max_width = 0
  237.                 for r in self.rows:
  238.                     max_width = max(max_width, len(r[x]))
  239.                 
  240.                 max_calc_widths.append(max_width)
  241.             
  242.             max_screen_width = None
  243.             if self.max_widths is None:
  244.                 max_screen_width = ttysize()[1]
  245.                 def_max = 8 * (max_screen_width / num_cols) / 10
  246.                 self.max_widths = []
  247.                 for c in self.header:
  248.                     self.max_widths.append(def_max)
  249.                 
  250.             elif len(self.max_widths) != num_cols:
  251.                 log.error('Invalid number of items in max col widths.')
  252.             
  253.             if self.min_widths is None:
  254.                 if max_screen_width is None:
  255.                     max_screen_width = ttysize()[1]
  256.                 
  257.                 def_min = 4 * (max_screen_width / num_cols) / 10
  258.                 self.min_widths = []
  259.                 for c in self.header:
  260.                     self.min_widths.append(def_min)
  261.                 
  262.             elif len(self.min_widths) != num_cols:
  263.                 log.error('Invalid number of items in min col widths.')
  264.             
  265.             col_widths = []
  266.             formats = []
  267.             for m1, m2, m3, m4 in zip(self.min_widths, min_calc_widths, self.max_widths, max_calc_widths):
  268.                 col_width = max(max(m1, m2), min(m3, m4))
  269.                 col_widths.append(col_width)
  270.                 formats.append({
  271.                     'width': col_width,
  272.                     'margin': self.margin })
  273.             
  274.             formatter = utils.TextFormatter(tuple(formats))
  275.             log.info(formatter.compose(self.header))
  276.             sep = []
  277.             for c in col_widths:
  278.                 sep.append('-' * c)
  279.             
  280.             log.info(formatter.compose(tuple(sep)))
  281.             for r in self.rows:
  282.                 log.info(formatter.compose(r))
  283.             
  284.         else:
  285.             log.error('No data rows')
  286.  
  287.  
  288. ALIGN_LEFT = 0
  289. ALIGN_CENTER = 1
  290. ALIGN_RIGHT = 2
  291.  
  292. def align(line, width = 70, alignment = ALIGN_LEFT):
  293.     space = width - len(line)
  294.     if alignment == ALIGN_CENTER:
  295.         return ' ' * (space / 2) + line + ' ' * (space / 2 + space % 2)
  296.     if alignment == ALIGN_RIGHT:
  297.         return ' ' * space + line
  298.     return line + ' ' * space
  299.  
  300.  
  301. def format_paragraph(paragraph, width = None, alignment = ALIGN_LEFT):
  302.     if width is None:
  303.         width = ttysize()[1]
  304.     
  305.     result = []
  306.     words = paragraph.split()
  307.     
  308.     try:
  309.         current = words[0]
  310.         words = words[1:]
  311.     except IndexError:
  312.         return [
  313.             paragraph]
  314.  
  315.     for word in words:
  316.         increment = 1 + len(word)
  317.         if len(current) + increment > width:
  318.             result.append(align(current, width, alignment))
  319.             current = word
  320.             continue
  321.         current = current + ' ' + word
  322.     
  323.     result.append(align(current, width, alignment))
  324.     return result
  325.  
  326.  
  327. def printer_table(printers):
  328.     header('SELECT PRINTER')
  329.     last_used_printer_name = user_conf.get('last_used', 'printer_name')
  330.     ret = None
  331.     table = Formatter(header = ('Num', 'CUPS Printer'), max_widths = (8, 100), min_widths = (8, 20))
  332.     default_index = None
  333.     for x, _ in enumerate(printers):
  334.         if last_used_printer_name == printers[x]:
  335.             table.add((str(x) + '*', printers[x]))
  336.             default_index = x
  337.             continue
  338.         table.add((str(x), printers[x]))
  339.     
  340.     table.output()
  341.     if default_index is not None:
  342.         (ok, i) = enter_range('\nEnter number 0...%d for printer (q=quit, <enter>=default: *%d) ?' % (x, default_index), 0, x, default_index)
  343.     else:
  344.         (ok, i) = enter_range('\nEnter number 0...%d for printer (q=quit) ?' % x, 0, x)
  345.     if ok:
  346.         ret = printers[i]
  347.     
  348.     return ret
  349.  
  350.  
  351. def device_table(devices, scan_flag = False):
  352.     header('SELECT DEVICE')
  353.     last_used_device_uri = user_conf.get('last_used', 'device_uri')
  354.     ret = None
  355.     if scan_flag:
  356.         table = Formatter(header = ('Num', 'Scan device URI'), max_widths = (8, 100), min_widths = (8, 12))
  357.     else:
  358.         table = Formatter(header = ('Num', 'Device URI', 'CUPS Printer(s)'), max_widths = (8, 100, 100), min_widths = (8, 12, 12))
  359.     default_index = None
  360.     device_index = { }
  361.     for x, d in enumerate(devices):
  362.         device_index[x] = d
  363.         if last_used_device_uri == d:
  364.             if scan_flag:
  365.                 table.add((str(x) + '*', d))
  366.             else:
  367.                 table.add((str(x) + '*', d, ','.join(devices[d])))
  368.             default_index = x
  369.             continue
  370.         if scan_flag:
  371.             table.add((str(x), d))
  372.             continue
  373.         table.add((str(x), d, ','.join(devices[d])))
  374.     
  375.     table.output()
  376.     if default_index is not None:
  377.         (ok, i) = enter_range('\nEnter number 0...%d for device (q=quit, <enter>=default: %d*) ?' % (x, default_index), 0, x, default_index)
  378.     else:
  379.         (ok, i) = enter_range('\nEnter number 0...%d for device (q=quit) ?' % x, 0, x)
  380.     if ok:
  381.         ret = device_index[i]
  382.     
  383.     return ret
  384.  
  385.  
  386. def connection_table():
  387.     ret = None
  388.     ios = {
  389.         0: ('usb', 'Universal Serial Bus (USB)') }
  390.     x = 1
  391.     if prop.net_build:
  392.         ios[x] = ('net', 'Network/Ethernet/Wireless (direct connection or JetDirect)')
  393.         x += 1
  394.     
  395.     if prop.par_build:
  396.         ios[x] = ('par', 'Parallel Port (LPT:)')
  397.         x += 1
  398.     
  399.     if len(ios) > 1:
  400.         header('SELECT CONNECTION (I/O) TYPE')
  401.         table = Formatter(header = ('Num', 'Connection Type', 'Description'), max_widths = (8, 20, 80), min_widths = (8, 10, 40))
  402.         for x, data in ios.items():
  403.             if x == 0:
  404.                 table.add((str(x) + '*', data[0], data[1]))
  405.                 continue
  406.             table.add((str(x), data[0], data[1]))
  407.         
  408.         table.output()
  409.         (ok, val) = enter_range('\nEnter number 0...%d for connection type (q=quit, enter=usb*) ? ' % x, 0, x, 0)
  410.         if ok:
  411.             ret = [
  412.                 ios[val][0]]
  413.         
  414.     else:
  415.         ret = [
  416.             'usb']
  417.     return ret
  418.  
  419.